#include <stdio.h>

#include "session.h"
#include "common_define.h"
#include "retcodes.h"
#include "log.h"

using namespace common;

int CSession::clear( )
{
	mOwnerObjID = INVALID_OBJ_ID;
	mDBSessionTimer = INVALID_OBJ_ID;
	mSessionDelete = true;

	is_clock_ = false;

	session_fun_ = NULL;

	return ::common::SUCCEED;
}


int CSession::Create( SessionProcessFun session_fun, SessionParameList parame, OBJ_ID_TYPE owner_obj_id, int64_t time_out )
{
	if ( session_fun == NULL )
	{
		return ::common::ERR_SESSION_FUN_IS_NULL;
	}

	mParame = parame;
	mOwnerObjID = owner_obj_id;
	session_fun_ = session_fun;

// 	TimerInit( time_out );
// 	TimerStart( );

	return ::common::SUCCEED;
}

void CSession::TimerActive( )
{
    if( NULL != session_fun_ )
    {
	    session_fun_( *this, true, NULL );
    }
	CSessionProcess::GetInstance( ).DestroySessionObject( get_id( ) );
}


CSessionProcess::CSessionProcess( )
{
}


OBJ_ID_TYPE CSessionProcess::AddSession(
	OBJ_ID_TYPE owner_obj_id,
	SessionProcessFun session_fun,
	SessionParameList parame,
	int time_out
	)
{
	CSession* session = CreateSessionObject( );
	if ( session == NULL )
	{
		LOG_ERROR("default","Cannt Get Session!");
		return INVALID_OBJ_ID;
	}

	int rtn = session->Create( session_fun, parame, owner_obj_id, time_out );
	if ( rtn != ::common::SUCCEED )
	{
		LOG_ERROR("default", "create session faild %d, fun %p", rtn, session_fun );
		return INVALID_OBJ_ID;
	}

	return session->get_id( );
}

void CSessionProcess::SessionProcess( OBJ_ID_TYPE session_obj_id, const CJsonMessageBase* response )
{
	CSession* session = GetSession( session_obj_id );
	if (session == NULL)
	{
		LOG_ERROR("default","Cannt Get Session By ObjID %d!", session_obj_id);
		return ;
	}

	if ( session->session_fun_ != NULL )
	{
		session->session_fun_( *session, false, response );
	}

	if ( session->mSessionDelete == true )
	{
		DestroySessionObject( session->get_id( ) );
	}

	return;
}